package db

import (
	"fmt"
	"golang-learning/gorm/variable"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"os"
	"time"
)

func GetMysqlDbConn() (db *gorm.DB, errR error) {
	/*看是否已经有连接了*/
	if variable.GormDbMysql != nil {
		fmt.Println("Mysql连接已存在直接使用")
		db = variable.GormDbMysql
		return
	}

	/*日志*/
	newLogger := logger.New(
		log.New(os.Stdout, "", log.LstdFlags), // io writer（日志输出的目标，前缀和日志包含的内容——译者注）
		logger.Config{
			SlowThreshold:             time.Second,   // 慢 SQL 阈值
			LogLevel:                  logger.Silent, // 日志级别
			IgnoreRecordNotFoundError: true,          // 忽略ErrRecordNotFound（记录未找到）错误
			Colorful:                  false,         // 禁用彩色打印
		},
	)

	dsn := "base:JieYiYun123@tcp(rm-uf64m74m539h5d7904o.mysql.rds.aliyuncs.com:3306)/base?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true, // 使用单数表名
		},
		Logger: newLogger,
	})

	if err != nil {
		fmt.Println(err)
		errR = err
		return
	} else {
		fmt.Println("connection succedssed")
	}

	/*连接池*/
	sqlDB, err := db.DB()
	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(100)
	sqlDB.SetConnMaxLifetime(time.Hour)

	if err != nil {
		fmt.Println(err)
		errR = err
		return
	}

	variable.GormDbMysql = db

	return
}
